package com.example.Service;

import com.example.utils.VivoAuth;
import org.json.JSONObject;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;

import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class VivoGPTService {
    private static final String APP_ID = "2025985389";
    private static final String APP_KEY = "eAkRKtYXOawsmtVv";
    private static final String URI = "/vivogpt/completions";
    private static final String DOMAIN = "api-ai.vivo.com.cn";
    private static final String METHOD = "POST";

    public String testVivoGPT(MultipartFile audioFile, String user) {
        String response = "";
        try {
            String base64Image = null;
            if (audioFile != null && !audioFile.isEmpty()) {
                // 1. 将上传的图片文件转换为base64
                byte[] imageBytes = audioFile.getBytes();
                base64Image = Base64.getEncoder().encodeToString(imageBytes);
            }

            String requestId = UUID.randomUUID().toString();

            // 2. 构建请求体
            Map<String, Object> data = new HashMap<>();
            data.put("sessionId", UUID.randomUUID().toString());
            data.put("requestId", requestId);


            if(audioFile != null && !audioFile.isEmpty()){
                data.put("model", "vivo-BlueLM-V-2.0");
            }else {
                data.put("model", "BlueLM-Vision-prd");
            }

            if(audioFile != null && !audioFile.isEmpty()){
                // 构建符合文档结构的messages数组
                @SuppressWarnings("unchecked")
                Map<String, Object>[] messages = new Map[2];
                messages[0] = new HashMap<>();
                messages[0].put("role", "user");
                messages[0].put("content", "data:image/JPEG;base64," + base64Image);
                messages[0].put("contentType", "image");

                messages[1] = new HashMap<>();
                messages[1].put("role", "user");
                messages[1].put("content", user);
                messages[1].put("contentType", "text");

                data.put("messages", messages);
            }else {
                // 构建消息数组
                Map<String, Object>[] messages = new Map[1];
                messages[0] = new HashMap<>();
                messages[0].put("role", "user");
                messages[0].put("content", user);
                messages[0].put("contentType", "text");

                data.put("messages", messages);

                // 添加模型参数
                Map<String, Object> extra = new HashMap<>();
                extra.put("temperature", 0.9f);
                extra.put("top_p", 0.7f);
                extra.put("max_tokens", 2048);
                extra.put("repetition_penalty", 1.02f);
                data.put("extra", extra);

                System.out.println("   请求体构建完成");
            }


            // 3. 生成签名头
            System.out.println("3. 开始生成签名头");
            String queryParams = "requestId=" + requestId;
            HttpHeaders headers = VivoAuth.generateAuthHeaders(APP_ID, APP_KEY, METHOD, URI, queryParams);
            headers.setContentType(MediaType.APPLICATION_JSON);

            System.out.println("   签名头信息：");
            headers.forEach((key, value) -> System.out.println("   " + key + ": " + value));

            // 4. 创建WebClient
            System.out.println("4. 创建WebClient");
            WebClient webClient = WebClient.builder()
                    .baseUrl("https://" + DOMAIN)
                    .defaultHeaders(httpHeaders -> httpHeaders.addAll(headers))
                    .build();

            long startTime = System.currentTimeMillis();

            // 5. 发送请求并处理响应
            System.out.println("5. 开始发送请求");
            response = webClient.method(HttpMethod.POST)
                    .uri(uriBuilder -> uriBuilder
                            .path(URI)
                            .queryParam("requestId", requestId)
                            .build())
                    .body(BodyInserters.fromValue(data))
                    .retrieve()
                    .onStatus(status -> !status.is2xxSuccessful(),
                            clientResponse -> clientResponse.bodyToMono(String.class)
                                    .map(errorBody -> {
                                        System.err.println("   请求失败，状态码: " + clientResponse.statusCode());
                                        System.err.println("   错误信息: " + errorBody);
                                        return new RuntimeException("请求失败: " + clientResponse.statusCode() + ", 错误信息: " + errorBody);
                                    }))
                    .bodyToMono(String.class)
                    .block();

            long endTime = System.currentTimeMillis();
            System.out.println("6. 收到响应: " + response);
            System.out.printf("   请求耗时: %.2f秒%n", (endTime - startTime) / 1000.0);
            System.out.println("=== 测试执行完成 ===");

            // 解析JSON响应并提取content字段
            JSONObject jsonResponse = new JSONObject(response);
            if (jsonResponse.has("data")) {
                JSONObject dataObj = jsonResponse.getJSONObject("data");
                if (dataObj.has("content")) {
                    return dataObj.getString("content");
                }
            }
            return "无法解析响应内容";
        } catch (IOException e) {
            System.err.println("图片读取失败: " + e.getMessage());
            return "图片处理失败";
        } catch (Exception e) {
            System.err.println("响应解析失败: " + e.getMessage());
            return "响应解析失败";
        }
    }
}
